<template>
  <div>
    <!-- 模块选择 -->
    <div class="module-selector">
      <el-radio-group v-model="activeModule" @change="handleModuleChange">
        <el-radio-button label="class">班级管理</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="query">
        <el-form-item label="班级ID">
          <el-input v-model="query.id" placeholder="请输入班级ID" clearable />
        </el-form-item>
        <el-form-item label="班主任">
          <el-input
              v-model="query.headName"
              placeholder="请输入班主任姓名"
              clearable
              style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="年级">
          <el-select
              v-model="query.grade"
              placeholder="请选择年级"
              clearable
              style="width: 120px"
          >
            <el-option
                v-for="grade in gradeOptions"
                :key="grade.value"
                :label="grade.label"
                :value="grade.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班级">
          <el-select
              v-model="query.classNum"
              placeholder="请选择班级"
              clearable
              style="width: 120px"
          >
            <el-option
                v-for="cls in classOptions"
                :key="cls.value"
                :label="cls.label"
                :value="cls.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="container">
      <!-- 工具栏按钮 -->
      <div class="toolbar-container">
        <el-button type="warning" :icon="CirclePlusFilled" @click="handleAdd">新增</el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedIds.length === 0">
          批量删除
        </el-button>
      </div>

      <!-- 表格区域 -->
      <el-table
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          border
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column type="index" label="序号" width="55" align="center" />
        <el-table-column prop="id" label="班级ID" width="120" align="center" />
        <el-table-column prop="grade" label="年级" width="100" align="center">
          <template #default="{row}">
            {{ getGradeLabel(row.grade) }}
          </template>
        </el-table-column>
        <el-table-column prop="classNum" label="班级" width="100" align="center">
          <template #default="{row}">
            {{ getClassLabel(row.classNum) }}
          </template>
        </el-table-column>
        <el-table-column prop="headName" label="班主任" width="120" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{row}">
            {{ getStatusLabel(row.status) }}
          </template>
        </el-table-column>
        <el-table-column prop="studentCount" label="学生人数" width="100" align="center" />


        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{row}">
            <el-button size="small" type="primary" @click="handleView(row)">查看</el-button>
            <el-button size="small" type="warning" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          v-model:current-page="page.index"
          v-model:page-size="page.size"
          :total="page.total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="changePage"
          @size-change="handleSizeChange"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
        :title="`${isEdit ? '编辑' : '新增'}班级`"
        v-model="visible"
        width="700px"
        destroy-on-close
        :close-on-click-modal="false"
        @close="closeDialog"
    >
      <el-form :model="rowData" label-width="100px" ref="formRef">
        <el-form-item label="班级ID" prop="id" required :rules="[{ required: true, message: '请输入班级ID', trigger: 'blur' }]">
          <el-input v-model="rowData.id" placeholder="格式: 年份+两位数字, 如202301" />
        </el-form-item>

        <el-form-item label="年级" prop="grade" required :rules="[{ required: true, message: '请选择年级', trigger: 'change' }]">
          <el-select v-model="rowData.grade" placeholder="请选择年级" style="width: 100%">
            <el-option
                v-for="grade in gradeOptions"
                :key="grade.value"
                :label="grade.label"
                :value="grade.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="班级" prop="classNum" required :rules="[{ required: true, message: '请选择班级', trigger: 'change' }]">
          <el-select v-model="rowData.classNum" placeholder="请选择班级" style="width: 100%">
            <el-option
                v-for="cls in classOptions"
                :key="cls.value"
                :label="cls.label"
                :value="cls.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="班主任" prop="teacherId" required :rules="[{ required: true, message: '请选择班主任', trigger: 'change' }]">
          <el-select v-model="rowData.teacherId" placeholder="请选择班主任">
            <el-option
                v-for="teacher in teacherSelectOptions"
                :key="teacher.value"
                :label="teacher.label"
                :value="teacher.value"
            />
          </el-select>
        </el-form-item>


        <el-form-item label="状态" prop="status" required :rules="[{ required: true, message: '请选择状态', trigger: 'change' }]">
          <el-select v-model="rowData.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="正常" value="正常" />
            <el-option label="冻结" value="冻结" />
          </el-select>
        </el-form-item>
      </el-form>

      <template v-if="rowData.assignedTeachers" style="width: 100%">
        <el-form-item
            v-for="(teacher, index) in rowData.assignedTeachers"
            :key="index"
            :label="`任课教师${index + 1}`"
            label-width="100px"
        >
          <el-select
              v-model="teacher.id"
              placeholder="请选择教师"
              style="width: 200px"
              @change="handleTeacherChange(teacher, index)"
          >
            <el-option
                v-for="opt in teacherSelectOptions"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
            />
          </el-select>
          <el-button type="danger" @click="removeAssignedTeacher(index)" style="margin-left: 10px">移除</el-button>
        </el-form-item>
        <el-form-item label=" " label-width="100px">
          <el-button type="primary" @click="addAssignedTeacher">添加任课教师</el-button>
        </el-form-item>
      </template>

      <template #footer>
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </template>

    </el-dialog>

    <!-- 查看详情弹窗 -->
    <el-dialog title="班级详情" v-model="detailVisible" width="700px" destroy-on-close>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="班级ID">{{ detailData.id }}</el-descriptions-item>
        <el-descriptions-item label="年级">{{ getGradeLabel(detailData.grade) }}</el-descriptions-item>
        <el-descriptions-item label="班级">{{ getClassLabel(detailData.classNum) }}</el-descriptions-item>
        <el-descriptions-item label="班主任">{{ detailData.headName }}</el-descriptions-item>
        <el-descriptions-item label="学生人数">{{ detailData.studentCount }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ getStatusLabel(detailData.status) }}</el-descriptions-item>

        <el-descriptions-item label="任课教师">
          {{ detailData.teachers?.map(t => t.realName).join('，') || '无' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>

</template>

<script setup lang="ts">
import { ref, reactive, computed ,onMounted} from 'vue';
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus';
import { CirclePlusFilled } from '@element-plus/icons-vue';
import {getClassList,createClass,updateClass,deleteClass,batchDeleteClass,getClassDetail, getAllTeachers} from "@/api/classes";
// 模块名称映射
const moduleNames = {
  class: '班级管理'
};

// 当前激活的模块
const activeModule = ref<'class'>('class');
const formRef = ref<FormInstance>();

const teacherSelectOptions = ref([]);
const detailData = ref<any>({});


//加载所有老师
const fetchAllTeachers = async () => {
  try {
    const res = await getAllTeachers();
    console.log(res);
    teacherSelectOptions.value = res.data.map(item => ({
      label: item.realName,
      value: item.id
    }));
  } catch (e) {
    console.log("获取失败");
    ElMessage.error('获取教师列表失败');
  }
};

const addAssignedTeacher = () => {
  rowData.value.assignedTeachers.push({ id: '', realName: '' });
};

const removeAssignedTeacher = (index) => {
  rowData.value.assignedTeachers.splice(index, 1);
};

const handleTeacherChange = (teacher, index) => {
  const selected = teacherSelectOptions.value.find(opt => opt.value === teacher.id);
  if (selected) {
    teacher.realName = selected.label;
  }
};

//查看班级详情
const fetchClassDetail = async (id: string) => {
  try {
    const res = await getClassDetail(id);
    detailData.value = res.data;
  } catch (e) {
    ElMessage.error('获取班级详情失败');
  }
};

// 下拉选项数据
const gradeOptions = [
  { label: '一年级', value: 1 },
  { label: '二年级', value: 2 },
  { label: '三年级', value: 3 },
  { label: '四年级', value: 4 },
  { label: '五年级', value: 5 },
  { label: '六年级', value: 6 }
];

const classOptions = [
  { label: '1班', value: 1 },
  { label: '2班', value: 2 },
  { label: '3班', value: 3 },
  { label: '4班', value: 4 },
  { label: '5班', value: 5 },
  { label: '6班', value: 6 },
];

// const teacherOptions = [
//   { id: 1, name: '张老师' },
//   { id: 2, name: '李老师' },
//   { id: 3, name: '王老师' },
//   { id: 4, name: '赵老师' },
//   { id: 5, name: '刘老师' }
// ];

const statusOptions = [
  { label: '正常', value: '正常' },
  { label: '冻结', value: '冻结' }
];

// 查询相关
const query = reactive({
  id: '',
  teacherId: '',
  grade: '',
  classNum: '',
  headName:''
});

// 获取年级标签
const getGradeLabel = (value: number | null | undefined) => {
  if (value === null || value === undefined) {
    return '毕业班';
  }
  const grade = gradeOptions.find(item => item.value === value);
  return grade ? grade.label : value;
};

// 获取班级标签
const getClassLabel = (value: number) => {
  const cls = classOptions.find(item => item.value === value);
  return cls ? cls.label : value;
};

// 获取状态标签
const getStatusLabel = (value: string) => {
  const status = statusOptions.find(item => item.value === value);
  return status ? status.label : value;
};

// 获取数据
const getData = async () => {
  try {
    const params = {
      ...query,
      page: page.index,
      pageSize: page.size
    };
    const res = await getClassList(params);
    tableData.value = res.data.list;
    page.total = res.data.total;
  } catch (e) {
    ElMessage.error("获取班级数据失败");
  }
};


const handleSearch = () => {
  changePage(1);
};

const resetSearch = () => {
  query.id = '';
  query.teacherId = '';
  query.grade = '';
  query.classNumber = '';
  changePage(1);
};

// 分页相关
const page = reactive({
  index: 1,
  size: 10,
  total: 0,
});

const tableData = ref([]);
const selectedIds = ref<string[]>([]);

const changePage = (val: number) => {
  page.index = val;
  getData();
};

const handleSizeChange = (val: number) => {
  page.size = val;
  getData();
};

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedIds.value = selection.map(item => item.id);
};

// 批量删除
const handleBatchDelete = async () => {
  await batchDeleteClass(selectedIds.value);
  ElMessage.success('批量删除成功');
  getData();
};
// const handleBatchDelete = () => {
//   if (selectedIds.value.length === 0) {
//     ElMessage.warning('请至少选择一条数据');
//     return;
//   }
//
//   ElMessageBox.confirm(`确定要删除选中的${selectedIds.value.length}条班级数据吗？`, '提示', {
//     confirmButtonText: '确定',
//     cancelButtonText: '取消',
//     type: 'warning'
//   }).then(() => {
//     mockData[activeModule.value] = mockData[activeModule.value].filter(
//         item => !selectedIds.value.includes(item.id)
//     );
//     ElMessage.success('删除成功');
//     getData();
//     selectedIds.value = [];
//   }).catch(() => {});
// };

// 弹窗相关
const visible = ref(false);
const detailVisible = ref(false);
const isEdit = ref(false);
const rowData = ref<any>({});

// 模块切换处理
const handleModuleChange = () => {
  resetSearch();
  changePage(1);
};

// 初始化新增数据
const initNewData = () => {
  return {
    id: '',
    classId: '',
    grade: '',
    classNum: '',
    teacherId: '',
    teacherName: '',
    status: '',
    assignedTeachers:[]
  };
};

// 新增按钮点击
const handleAdd = async () => {
  await fetchAllTeachers();
  isEdit.value = false;
  rowData.value = initNewData();
  visible.value = true;
};

//编辑按钮点击
const handleEdit = async (row: any) => {
  await fetchAllTeachers();
  isEdit.value = true;

  const res = await getClassDetail(row.id);
  const detail = res.data;
  rowData.value = {
    ...detail,
    teacherId: row.headTeacher,
    assignedTeachers: (detail.teachers || []).map(t => ({
      id: t.id,
      realName: t.realName
    }))
  };

  visible.value = true;
};

// 查看按钮点击
const handleView = async (row: any) => {
  try {
    await fetchClassDetail(row.id);
    detailVisible.value = true;
  } catch (e) {
    ElMessage.error("获取班级详情失败");
  }
};


// 确认提交
const handleConfirm = async () => {
  try {
    // 验证表单
    await formRef.value?.validate();

    const submitData = {
      ...rowData.value,
      headTeacher: rowData.value.teacherId,
      teachers:  rowData.value.assignedTeachers.map(t => t.id)
    };

    if (isEdit.value) {
      await updateClass(submitData);
      ElMessage.success('编辑成功');
    } else {
      await createClass(submitData);
      ElMessage.success('新增成功');
    }


    // 关闭弹窗并刷新数据
    visible.value = false;
    getData();
  } catch (error) {
    console.log('表单验证失败', error);
  }
};

const closeDialog = () => {
  visible.value = false;
};

// 删除单条数据
// const handleDelete = (row: any) => {
//   ElMessageBox.confirm('确定要删除该班级数据吗？', '提示', {
//     confirmButtonText: '确定',
//     cancelButtonText: '取消',
//     type: 'warning'
//   }).then(() => {
//     mockData[activeModule.value] = mockData[activeModule.value].filter(
//         item => item.id !== row.id
//     );
//     ElMessage.success('删除成功');
//     getData();
//   }).catch(() => {});
// };
const handleDelete = async (row: any) => {
  await ElMessageBox.confirm('确定要删除该班级数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  });

  await deleteClass(row.id);
  ElMessage.success('删除成功');
  getData();
};

onMounted(() => {
  fetchAllTeachers();
});

// 初始化加载数据
getData();
</script>

<style scoped>
.module-selector {
  margin-bottom: 20px;
  padding: 10px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.search-container {
  padding: 20px;
  background: #fff;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.container {
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  position: relative;
}

.toolbar-container {
  margin-bottom: 20px;
  text-align: right;
}

.el-table {
  margin-bottom: 15px;
  width: 100%;
}

.el-pagination {
  justify-content: flex-end;
  margin-top: 15px;
}

/* 确保表格列宽总和与表格宽度匹配 */
:deep(.el-table__header) {
  width: 100% !important;
}

:deep(.el-table__body) {
  width: 100% !important;
}
</style>
